<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所在城市" prop="address">
        <el-input v-model="queryParams.address" placeholder="景点地址/城市/景点名字" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="分类" clearable>
          <el-option v-for="dict in categoryList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option v-for="dict in dict.type.sys_number" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:Attraction:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AttractionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="景点名字" align="center" prop="attractionName" />
      <el-table-column v-if="shouldShowColumn('city')" label="所在城市" align="center" prop="city" />
      <el-table-column v-if="shouldShowColumn('address')" label="地址" align="center" prop="address" />
      <el-table-column label="介绍" align="center" prop="description" />
      <el-table-column v-if="shouldShowColumn('views')" label="浏览量" align="center" prop="views" />
      <el-table-column label="评分" align="center" prop="rating" />
      <el-table-column label="开放时间" align="center" prop="openTime" />
      <el-table-column v-if="shouldShowColumn('price')" label="票价" align="center" prop="price" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:Attraction:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="openImage(scope.row)">图片</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:Attraction:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="景点名字" prop="attractionName">
          <el-input v-model="form.attractionName" placeholder="请输入景点名字" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="分类" clearable>
            <el-option v-for="dict in categoryList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="景点地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入景点地址" />
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input v-model="form.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="价格" />
        </el-form-item>
        <el-form-item label="开放时间" prop="openTime">
          <el-input v-model="form.openTime" placeholder="开放时间" />
        </el-form-item>

        <el-form-item label="详细描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="Image" width="500px" append-to-body>
        <div style="display: flex; flex-wrap: wrap;gap: 10px;">
          <el-upload :action="`${base_url}/common/upload`" list-type="picture-card" :file-list="fileList"
            :on-success="handleAvatarSuccess" :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>

        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttraction, getAttraction, delAttraction, addAttraction, updateAttraction, listAttractionImage,addAttractionImage,delAttractionImage } from "@/api/system/attraction";

import { getCategory } from "@/api/system/category";
export default {
  name: "Attraction",
  dicts: ['sys_normal_disable', 'sys_number'],
  data() {
    return {
      base_url: process.env.VUE_APP_BASE_API,
      dateRange: [],
      categoryList: [],
      columnsToShow: ['city', 'address', 'views', 'openTime', 'price'],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      AttractionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      Image: false,
      fileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: 1,
        status: 2,
        address: undefined,
        categoryId: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        AttractionName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
        AttractionCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" }
        ],
        AttractionSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCategory();

  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      
      addAttractionImage({ attractionId: this.attractionId, attractionPhoto: res.fileName }).then(response => {
        console.log(response);
        if(response.code == 200){
          this.$modal.msgSuccess("新增成功");
          this.Image = false;
          if(     this.queryParams.status == '' && this.queryParams.categoryId == ''){
            this.queryParams.status = 2
            this.queryParams.categoryId = 0
          }
          this.getList();
        }else{
          this.$modal.msgError("新增失败");
        }
        
      })
    },
    handleRemove(file, fileList) {
      console.log(file.photoId);
      delAttractionImage(file.photoId).then(response => {
        if(response.code == 200){
          this.$modal.msgSuccess("新增成功");
          this.Image = false;
          if(     this.queryParams.status == '' && this.queryParams.categoryId == ''){
            this.queryParams.status = 2
            this.queryParams.categoryId = 0
          }
          this.getList();
        }else{
          this.$modal.msgError("新增失败");
        }
      })
    },

    openImage(row) {
      this.attractionId = row.attractionId;
      listAttractionImage({ attractionId: row.attractionId }).then(response => {
        console.log(response.data);

        // 更新 fileList 数据
        this.fileList = response.data.map(item => {
            item.url = process.env.VUE_APP_BASE_API +  item.attractionPhoto;
            return item;
        })
        ;
        console.log(this.fileList);

        // 在数据请求完成并成功更新 fileList 后，设置 Image 为 true
        this.Image = true;
      }).catch(error => {
        console.error("获取景点图片失败", error);
        // 可以在这里处理错误，比如显示错误消息或者记录日志
      });
    },
    getCategory() {
      getCategory().then(response => {
        this.categoryList = response.data.map(item => {
          item.value = item.categoryId
          item.label = item.categoryName
          return item
        })
      })
    },
    shouldShowColumn(column) {
      // 检查columnsToShow数组中是否包含当前列名，并确保至少有一条记录包含此字段的值。
      if (!this.columnsToShow.includes(column)) return false;

      for (let item of this.AttractionList) {
        if (item[column]) return true;
      }
      return false;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listAttraction(this.queryParams).then(response => {

        this.AttractionList = response.data.list;
        this.total = response.data.total;
            this.queryParams.status = ''
    this.queryParams.categoryId = ''
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attractionNameL: undefined,
        categoryId: 1,
        addressL: undefined,
        city: undefined,
        price: undefined,
        openTime: undefined,
        description: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(     this.queryParams.status == '' && this.queryParams.categoryId == ''){
            this.queryParams.status = 2
            this.queryParams.categoryId = 0
          }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.AttractionId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加景点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log(row);

      const AttractionId = row.attractionId
      getAttraction(AttractionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改景点";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title == '修改景点') {
            updateAttraction(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              if(     this.queryParams.status == '' && this.queryParams.categoryId == ''){
            this.queryParams.status = 2
            this.queryParams.categoryId = 0
          }
              this.getList();
            });
          } else {
            addAttraction(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if(     this.queryParams.status == '' && this.queryParams.categoryId == ''){
            this.queryParams.status = 2
            this.queryParams.categoryId = 0
          }
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const AttractionIds = row.attractionId || this.ids;
      this.$modal.confirm('是否确认删除岗位编号为"' + AttractionIds + '"的数据项？').then(function () {
        return delAttraction(AttractionIds);
      }).then(() => {
        if(     this.queryParams.status == '' && this.queryParams.categoryId == ''){
            this.queryParams.status = 2
            this.queryParams.categoryId = 0
          }
        this.getList();
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/Attraction/export', {
        ...this.queryParams
      }, `Attraction_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
